package com.tastesport.chat.schedule;//package com.tastesport.chat.schedule;

import lombok.extern.log4j.Log4j;
import org.jim.common.ImAio;
import org.jim.common.ImConst;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.cache.redis.RedisCacheManager;
import org.springframework.stereotype.Component;

import java.util.*;


/**
 * @author dc
 * @title: HeartTask
 * @projectName nb_chat_core
 * @description: TODO
 * @date 2019/7/514:31
 */
@Component
@Log4j
public class HeartTask {

    RedisCache HeartCache = RedisCacheManager.register(ImConst.HEART, Integer.MAX_VALUE, Integer.MAX_VALUE);
    RedisCache userCache = RedisCacheManager.register(ImConst.USER, Integer.MAX_VALUE, Integer.MAX_VALUE);

    //    @Scheduled(cron = "* * 0/2 * * *")
    private void wrok() {

        Map<String, String> map = new HashMap<>();
        try {
            map = HeartCache.hashGet("user");
        } catch (Exception e) {
            return;
        }
        Iterator<String> it = map.keySet().iterator();
        Long time = new Date().getTime();
        List<String> num = new ArrayList<>();
        while (it.hasNext()) {
            String key = it.next();
            Long value = Long.parseLong(map.get(key));
            if ((time - value) > 12000) {
                ImAio.remove(key, "");
                ImAio.unbindUser(key, null);
                num.add(key);
                userCache.put(key + ":terminal:ws", "offline");
                System.out.println("心跳超时断开:" + key);
            }
        }
        if (num.size() == 0) {
            return;
        }
        String[] deluser = new String[num.size()];
        for (int i = 0; i < num.size(); i++) {
            deluser[i] = num.get(i);
        }
        HeartCache.hashDel("user", deluser);


    }
}
